# ********************************************
# * Player / Stage Connection Script         *
# * Authors: André Bannwart Perina           *
# *          Antonio Canabrava Fraideinberze *
# *          Willian Felipe Lopes da Silva   *
# ******************************************** 

if [ $# -ne 3 ]; then
	echo "Usage: $0 portNumber numIters startIndex"
	exit
fi

# Sets the port to be used
port=$1

# Runs the loop the number of iterations/individuals
c=$3
while (( $c < $2+$3 ))
do
    # Gets the number of ports being used
    number=$(netstat -i net --tcp -l p | awk '{print $2}' | wc -l)

    # Checks if the port passed as argument is being used, if so, gets the next available
    for (( i=2; $i <= $number; i++ ))
    do
        ports[$i]=$(netstat -i net --tcp -l p | awk '{print $2}' | awk "NR==$i{print;exit}")

        while (( "${ports[$i]}" == "$port" ))
        do
            let port=$port+1
        done
    done

    # Starts the simulator
    echo "Running player with simple.cfg..."
    player -p $1 player/simple.cfg &
    sleep 1.3

    # Runs the algorithm to move the robot
    echo "Running the controller..."
    ./bin/main $1 deltaFiles/file_$(($c)) fitnessFiles/file_$(($c)) 1.5 0.01 0.1 2.0 2.0

    # Kills any instance of that is still running
    echo "Killing it..."
    killall player
    c=$((c+1))
    while [ $(ps aux | grep " player -p $1 " | wc -l) -gt 1 ]
	do
		killall player
	done
done
